/*
 * @Author: shiguo
 * @Date: 2022-05-05 14:52:53
 * @LastEditors: shiguo
 * @LastEditTime: 2023-01-03 17:50:43
 * @FilePath: /@aks-dev/easyui/lib/Echarts/EchartsView.tsx
 */
import * as React from 'react'
import { MeasureOnSuccessCallback, StyleSheet, View, ViewStyle } from 'react-native'
import { WebView } from 'react-native-webview'
import { EchartsViewProps } from '.'
import { getHtml, toString } from './helper'

type State = {
    width: number;
    height: number;
    isLoaded: boolean;
}


type Reducer = (prevState: State, action: Partial<State>) => State


const EchartsView: React.FC<EchartsViewProps> = (props) => {
    const [state, dispatch] = React.useReducer<Reducer>(
        (prevState, action) => Object.assign({}, prevState, action),
        {
            width: 0,
            height: 0,
            isLoaded: false
        }
    )
    const WebViewRef: React.MutableRefObject<{ injectJavaScript: Function }> = React.useRef() as any
    const containerRef = React.useRef<{ measure: (callback: MeasureOnSuccessCallback) => void }>()
    const rootView = React.useRef<{
        pageX: number;
        pageY: number;
        height: number;
        width: number;
    }>({ pageX: 0, pageY: 0, width: 0, height: 0 })
    const getRootViewlayoutPromise = () => {
        return new Promise((resovle, reject) => {
            containerRef.current?.measure((...args) => {
                if (args.length == 6) {
                    rootView.current = {
                        width: args[2],
                        height: args[3],
                        pageX: args[4],
                        pageY: args[5],
                    }
                }
                // console.log('RootView', rootView.current)
                resovle(args)
            })
        })
    }


    React.useLayoutEffect(() => {
        ; (async () => {
            if (state.isLoaded) {
                await getRootViewlayoutPromise()
                let height = rootView.current.height ? `${rootView.current.height}px` : 'auto'
                let width = rootView.current.width ? `${rootView.current.width}px` : 'auto'
                const run = `
                ;(function() {
                    var instance = echarts.getInstanceByDom(document.getElementById('main'));
                    if(instance == null){
                        document.getElementById('main').style.height = "${height}";
                        document.getElementById('main').style.width = "${width}";
                        instance = echarts.init(document.getElementById('main'));
                    }
                    instance.clear();
                    instance.setOption(${toString(props.option)});
                })();
                `
                WebViewRef.current?.injectJavaScript(run);

                return () => {
                    const run = `
                    ;(function() {
                        var instance = echarts.getInstanceByDom(document.getElementById('main'));
                        instance.clear();
                        if(!instance.isDisposed()){
                            instance.dispose();
                        }
                    })();
                    `

                    WebViewRef.current?.injectJavaScript(run);
                }
            }
            return undefined
        })().catch(err => {
            console.log(err)
        })


    }, [props.option, state.isLoaded])



    // const injectedJavaScript = (): string => {
    //     console.log('injectedJavaScript', props.option.xAxis.data)
    //     let height = state.height ? `${state.height}px` : 'auto'
    //     let width = state.width ? `${state.width}px` : 'auto'
    //     return `
    //             ;(function() {
    //                 document.getElementById('main').style.height = "${height}";
    //                 document.getElementById('main').style.width = "${width}";
    //                 var instance = echarts.getInstanceByDom(document.getElementById('main'));
    //                 if(instance == null){
    //                      instance = echarts.init(document.getElementById('main'));
    //                 }
    //                 instance.clear();
    //                 instance.setOption(${toString(props.option)});
    //                 instance.on('click', function(params) {
    //                     var seen = [];
    //                     var paramsString = JSON.stringify(params, function(key, val) {
    //                     if (val != null && typeof val == "object") {
    //                         if (seen.indexOf(val) >= 0) {
    //                         return;
    //                         }
    //                         seen.push(val);
    //                     }
    //                     return val;
    //                     });
    //                    // window.ReactNativeWebView.postMessage(JSON.stringify({"types":"ON_PRESS","payload": paramsString}));
    //                 });
    //             })();
    //             `
    // }



    return (
        <View style={[styles.container, props.style]} ref={containerRef as any}>
            <WebView
                ref={WebViewRef as any}
                originWhitelist={['*']}
                useWebKit={true}  // ios使用最新webkit内核渲染
                allowUniversalAccessFromFileURLs={true}
                geolocationEnabled={true}
                mixedContentMode={'always'}
                renderLoading={() => {
                    if (props.renderLoading) return props.renderLoading()
                    return <View style={{ backgroundColor: (props.style as ViewStyle)?.backgroundColor || 'transparent' }} />
                }} // 设置空View，修复ioswebview闪白
                style={{
                    backgroundColor: (props.style as ViewStyle)?.backgroundColor || 'transparent',
                    opacity: 0.99,//解决闪退的办法
                }} // 设置背景色透明，修复android闪白
                scrollEnabled={false}
                // onMessage={e=>{
                //     console.log(e)
                // }}
                javaScriptEnabled={true}
                // injectedJavaScript={injectedJavaScript()}
                startInLoadingState={false}
                onLoadEnd={(_) => {
                    dispatch({ isLoaded: true })
                    // console.log('onLoadEnd')
                }}
                onError={e => {
                    console.log('onError', e)
                }}
                source={{
                    baseUrl: '',
                    html: getHtml({ backgroundColor: (props.style as ViewStyle)?.backgroundColor || 'transparent' })
                }}
            />
        </View>
    )

}

const styles = StyleSheet.create({
    container: {
        display: 'flex',
        flexGrow: 0,
        backgroundColor: 'white'
    }
})





export default EchartsView
// React.memo(EchartsView)
